var express = require("express");
var router = express.Router();

const userModel = require("../../models/usermodel");
const MD5 = require("MD5");

//加载注册页面
router.get("/reg", (req, res, next) => {
  res.render("auth/reg");
});

//保存注册信息
router.post("/reg", (req, res, next) => {
  userModel
    .create({ ...req.body, password: MD5(req.body.password) })
    .then((result) => {
      res.send("添加成功");
    })
    .catch((err) => {
      console.log(err);
    });
});

//加载登录页面
router.get("/login", (req, res, next) => {
  res.render("auth/login");
});

//验证登录信息
router.post("/login", (req, res, next) => {
  let { username, password } = req.body;

  userModel
    .findOne({ username: username, password: MD5(password) })
    .then((data) => {
      if (!data) {
        res.send("用户名或密码错误");
        return;
      }
      console.log(req.session);

      //设置 session 信息
      req.session.username = data.username;
      req.session._id = data._id;
      res.redirect("/account");
    })
    .catch((err) => {
      res.render("error", {
        message: "登录失败",
        error: { status: 500, stack: "用户名或密码错误" },
      });
    });
});

//验证登录信息
router.get("/loginout", (req, res, next) => {
  req.session.destroy(() => {
    res.redirect("/auth/login");
  });
});

module.exports = router;
